package com.hc.listener;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.hc.domain.User;
import com.hc.mapper.UserMapper;
import lombok.Getter;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 批量添加
 * @author zhitb
 */
@Log4j2
@Service
public class UserExcelListener extends AnalysisEventListener<User> {

	@Resource
	private UserMapper userMapper;

	/**
	 * 批处理阈值
	 */
	private static final int BATCH_COUNT = 250;
	@Getter
	List<User> list = new ArrayList<>(BATCH_COUNT);

	@Override
	public void invoke(User user, AnalysisContext analysisContext) { //逐行读取数据
		log.info("********** 解析到一条数据:{}", JSON.toJSONString(user));
		user.setAvatar("http://bing-images.oss-cn-beijing.aliyuncs.com/aa/bb/male1638154958151.jpg");
		list.add(user);
		if (list.size() >= BATCH_COUNT) {
            System.out.println("已经解析"+list.size()+"条数据");
			//每250条，往数据库中存一次
			int batchInsertRes = userMapper.batchInsert(list);
			System.out.println(batchInsertRes);
			list.clear();
		}
	}

	@Override
	public void doAfterAllAnalysed(AnalysisContext analysisContext) {
		log.info("**********所有数据解析完成！");
	}

}